package com.sctvcloud.bazhong.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.IShares;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.application.Cache;
import com.sctvcloud.bazhong.application.Constances;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.beans.EarnIntegralRule;
import com.sctvcloud.bazhong.beans.InvitationRuleVo;
import com.sctvcloud.bazhong.beans.UserInfoBean;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.ui.adapter.EarnIntegralAdapter;
import com.sctvcloud.bazhong.ui.dialog.ShareFragmentView;
import com.sctvcloud.bazhong.ui.utils.TitleUtils;
import com.sctvcloud.bazhong.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 赚取积分
 */
public class EarnIntegralActivity extends BaseActivity implements EarnIntegralAdapter.OnItemBtnClick {

    public static final String SHARE_TAG = "share_fragment_view";
    public static final int TO_SIGN_IN = 1;
    private static final int TO_LOGIN = 2;
    private static final String DOWNLOAD_APP_ADDRESS = "http://jrbzfile.bzitv.cn/sctv/logo/download/download.html";//http://app.hicloud.com/app/C100559361";//http://android.myapp.com/myapp/detail.htm?apkName=com.sctvcloud.bazhong";
    private static final String ruleUrl = "sctv/scgcmall/rule/index.json";
    @BindView(R.id.user_integral)
    protected CustomFontTextView userIntegral;
    @BindView(R.id.rule_content_view)
    protected RecyclerView ruleRecycler;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;

    private ArrayList<Pair<String, String>> pairs;
    private ShareFragmentView shareFragment;
    private EarnIntegralAdapter adapter;
    private List<EarnIntegralRule> ruleList = new ArrayList<>();

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        if (null != backImg) {
            backImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (null != msg) {
                    int what = msg.what;
                    switch (what) {
                        case TO_LOGIN:
                            toLoginView();
                            break;
                    }
                }
            }
        };
        initView();
        initUserData();
        requestRuleData();



    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_earn_integral);
        ButterKnife.bind(this);
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void initView() {
        userIntegral.setText("0");

        ruleRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        ruleRecycler.setItemAnimator(new DefaultItemAnimator());
        adapter = new EarnIntegralAdapter(this, ruleList, this);
        ruleRecycler.setAdapter(adapter);
    }

    /**
     * 请求用户相关数据，积分等
     */
    private void initUserData() {
        if (UserManager.getInstance().getUser() != null) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                    userIntegral.setText("" + userInfoBean.getIntegral());
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }

                @Override
                public boolean whenLoginExpiredBackGround() {
                    Message msg = new Message();
                    msg.what = TO_LOGIN;
                    handler.sendMessage(msg);
                    return true;
                }
            });
        } else {
            toLogin();
        }
    }

    private void toLoginView() {
        Toast.makeText(EarnIntegralActivity.this, "登录用户失效，请重新登录！", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    /**
     * 请求积分规则
     */
    private void requestRuleData() {

        NetUtils.getNetAdapter().getInvitationRuleList(getOwnerName(), Constances.MALL_ST_BASE_URL + ruleUrl, new AbsNetCallBack<InvitationRuleVo>(InvitationRuleVo.class) {
            @Override
            public void onSuc(InvitationRuleVo vo) {
                if (null != vo.getListInfo()) {
                    ruleList = vo.getListInfo();
                    adapter.setDataList(ruleList);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    public void onItemBtnClick(String type) {

        if (EarnIntegralAdapter.SIGN_IN.equalsIgnoreCase(type)) {
            //需要先登录
            if (UserManager.getInstance().getUser() != null) {
                JLog.e("mineClick", "签到");
                GridsumWebDissector.getInstance().trackEvent(this, "", "签到", "", 200, pairs);
                Intent signIn = new Intent(this, SignInActivity.class);
                startActivityForResult(signIn, TO_SIGN_IN);
            } else {
                toLogin();
            }
        } else if (EarnIntegralAdapter.SHARE_INVITATION.equalsIgnoreCase(type)) {
            if (null != Cache.getInstance().getUserInfo() && !TextUtils.isEmpty(Cache.getInstance().getUserInfo().getInvitationCode())) {
                shareFragment = new ShareFragmentView("" + Cache.getInstance().getUserInfo().getInvitationCode(), null);

                shareFragment.setOnShareAppClickListener(new ShareFragmentView.OnShareAppClickListener() {
                    @Override
                    public void onClick(Pair<String, String> pair) {
                        pairs = new ArrayList<>();
//                    if (null != pairsParent) {
//                        pairs.addAll(pairsParent);
//                    }
                        pairs.add(pair);
                        GridsumWebDissector.getInstance().trackEvent(EarnIntegralActivity.this, "", "分享APP", "", 200, pairs);
                    }
                });
                FragmentManager fm = getSupportFragmentManager();
                shareFragment.setDownloadAppAddress(DOWNLOAD_APP_ADDRESS);
                shareFragment.show(fm, SHARE_TAG);
                fm.executePendingTransactions();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TO_SIGN_IN || (requestCode == CODE_REQUEST_LOGIN && resultCode == RESULT_OK)) {
            //从签到页面回来刷新积分数据
            initUserData();
        }
    }
}
